<?php

namespace app\admin\controller;

use app\admin\constants\CacheConstants;
use app\model\AdminModel;
use app\model\AdminRolesModel;
use app\model\AdminRulesModel;
use Shopwwi\LaravelCache\Cache;
use support\Request;

class RulesController
{


    //管理员列表
    public function getAdminList(Request $request){

        $params = $request->all();

        $list = AdminModel::where(function($query) use ($params){

            if($params['username']){
                $query->where("username",'like',$params['username']."%");
            }
            if($params['realname']){
                $query->where("realname",'like',$params['realname']."%");
            }

        })->hidden(['password'])->select()->each(function($item,$key){

            $ids = explode(",",$item->roles);
           
            //$items[$k]['role'] = array_map('intval',$ids);
            $item->roles = array_map('intval',$ids);

        });

        return success('ok',$list);
    }
    //管理员添加
    public function addAdmin(Request $request){

        $params = $request->post();

        if(!$params['username'] || !$params['password']){
            return error('参数错误');
        }

        if(AdminModel::where("username",$params['username'])->find()){
            return error('账号重复');
        }

        $data = [
            'username'=>$params['username'],
            'realname'=>$params['realname'] ?? '',
            'password'=>get_password($params['password']),
            'status'=>$params['status'] ?? 1,
            'roles'=>implode(",",$params['roles']) ?? '',
        ];

        AdminModel::create($data);

        return success('操作成功');
    }
    
    //管理员编辑
    public function editAdmin(Request $request){

        $params = $request->post();

        if(!$params['username'] || !$params['id']){
            return error('参数错误');
        }

        if($params['id'] == 1) return error('无法编辑总管理员');

        if(AdminModel::where("username",$params['username'])->where("id",'<>',$params['id'])->find()){
            return error('账号重复');
        }

        $model = new AdminModel();

        $info = $model->find($params['id']);

        if(!$info) return error('数据不存在');

        $data = [
            'username'=>$params['username'],
            'realname'=>$params['realname'] ?? '',
            'status'=>$params['status'] ?? 1,
            'roles'=>implode(",",$params['roles']) ?? '',
        ];

        if($params['password']){
            $data['password'] = get_password($params['password']);
        }

        $info->save($data);

        //更新用户缓存、权限缓存、菜单缓存
        get_admin_info($params['id'],true);
        Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->flush();
        Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->flush();

        return success('操作成功');
    }
    //管理员删除
    public function delAdmin(Request $request){

        $id = $request->input('id');

        if(!$id || $id == 1){
            return error('参数错误');
        }

        $model = new AdminModel();

        $info = $model->find($id);

        $info->delete();

        //TODO 清理缓存
        Cache::delete('admin_info_'.$id);

        return success('操作成功');

    }

    //角色列表(分页)
    public function getRoleList(Request $request){

        $params = $request->all();
        $model = new AdminRolesModel();

        $limit = $request->input('limit',10);

        $list = $model->where(function($query) use ($params){
            $query->where("name",'like',$params['name']."%");
        })->paginate($limit)->each(function($item,$key){

            $rules = explode(",",$item->rules);
            $item->menu = array_map('intval',$rules);
        });

        return success('ok',$list);
    }
    //角色列表(全部,用于管理员选择角色使用)
    public function getRoleAllList(Request $request){

        return success('ok',AdminRolesModel::field("id as value,name as label")->select());
    }
    //角色添加
    public function addRole(Request $request){

        $params = $request->post();

        $menu = implode(",",array_unique($params['menu']['checked'] ?? $params['menu']));

        $data = [
            'name'=>$params['name'],
            'rules'=>$menu ?? ''
        ];
       
        AdminRolesModel::create($data);

        return success('操作成功');
    }
    //角色编辑
    public function editRole(Request $request){

        $params = $request->post();

        if(!$params['id']) return error('参数错误');

        if($params['id'] == 1) return error('无法编辑超级管理员');

        $model = new AdminRolesModel();

        $info = $model->find($params['id']);

        if(!$info) return error('数据不存在');

        $menu = implode(",",array_unique($params['menu']['checked'] ?? $params['menu']));

        $data = [
            'name'=>$params['name'],
            'rules'=>$menu ?? ''
        ];

        $info->save($data);

        Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->flush();
        Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->flush();

        return success('操作成功');
    }
    //角色删除
    public function delRole(Request $request){

        $id = $request->input('id');

        if(!$id) return error('参数错误');

        if($id == 1) return error('无法编辑超级管理员');

        $model = new AdminRolesModel();

        $info = $model->find($id);

        if(!$info) return error('数据不存在');

        $info->delete();

        Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->flush();
        Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->flush();

        return success('操作成功');
    }


    //菜单添加
    public function addMenu(Request $request){

        $params = $request->post();

        if(!$params['title'] || !in_array($params['type'],[1,2])){
            return error('参数错误');
        }

        //验证name唯一
        if($params['type'] == 1){
            if(AdminRulesModel::where("type",1)->where("name",$params['name'])->find()){
                return error('name重复');
            }
        }

        $data = [
            'path'=>$params['path'] ?? '',
            'pid'=>$params['pid'],
            'name'=>$params['name'] ?? '',
            'title'=>$params['title'] ?? '',
            'hide_menu'=>$params['hide_menu'] ?? '',
            'component'=>$params['component'] ?? '',
            'sort'=>$params['sort'] ?? 0,
            'type'=>$params['type'],
            'icon'=>$params['icon'] ?? '',
        ];

        $model = new AdminRulesModel();

        $model->save($data);

        Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->flush();
        Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->flush();

        return success('添加成功');
    }
    //菜单编辑
    public function editMenu(Request $request){

        $params = $request->post();

        if(!$params['title'] || !$params['id'] || !in_array($params['type'],[1,2])){
            return error('参数错误');
        }

        //验证name唯一
        if($params['type'] == 1){
            if(AdminRulesModel::where("type",1)->where("id",'<>',$params['id'])->where("name",$params['name'])->find()){
                return error('name重复');
            }
        }


        $model = new AdminRulesModel();
        $info = $model->find($params['id']);

        if(!$info) return error('数据不存在');

        $data = [
            'path'=>$params['path'] ?? '',
            'pid'=>$params['pid'],
            'name'=>$params['name'] ?? '',
            'title'=>$params['title'] ?? '',
            'hide_menu'=>$params['hide_menu'] ?? '',
            'component'=>$params['component'] ?? '',
            'sort'=>$params['sort'] ?? 0,
            'type'=>$params['type'],
            'icon'=>$params['icon'] ?? '',
        ];

        $info->save($data);

        Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->flush();
        Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->flush();

        return success('编辑成功');
    }
    //菜单删除
    public function delMenu(Request $request){

        $id = $request->input('id');

        if(!$id) return error('参数错误');

        //验证是否有下级
        if(AdminRulesModel::where("pid",$id)->find()){
            return error('请先删除下级菜单');
        }
        $model = new AdminRulesModel();
        $info = $model->find($id);

        if(!$info) return error('数据不存在');

        $info->delete();

        Cache::tags(CacheConstants::TAG_ADMIN_RULES_IDS)->flush();
        Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->flush();

        return success('删除成功');
    }
    //获取菜单列表
    public function getList(Request $request){

        $params = $request->all();

        $model = new AdminRulesModel();

        $list = $model->where(function($query) use($params){

            if(!empty($params['title'])){
                $query->where("title",'like',$params['title']."%");
            }

        })->order("sort desc")->column('*','id');

        $newlist = [];

        foreach($list as $k=>$v){

            if($v['pid'] && $list[$v['pid']]){
                $list[$v['pid']]['children'][] = &$list[$k];
            }else{
                $newlist[] = &$list[$k];
            }
        }




        return success('ok',$newlist);
    }

}
